package com.link.auth.base.user.controller;

import com.link.auth.base.user.model.User;
import com.link.auth.util.FunctionTimeUtil;
import com.link.auth.util.TrueOrFalse;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    private static final String ACCESS_TOKEN_SECONS = "access_token_seconds:";

    @Resource
    private RedisConnectionFactory connectionFactory;

    @Resource
    private TrueOrFalse trueOrFalse;

    @RequestMapping(value = "/test")
    public Map<String, Object> test() {
        Map<String, Object> result = new HashMap<>();
        result.put("code", "AUTH-USER-001");
        result.put("message", "[AUTH-USER-001]错误信息!");
        System.out.println(result);
        return result;
    }

    @RequestMapping(value = "/current")
    public User getUser(Principal principal) {
        long currentBegin = System.currentTimeMillis();
        RedisConnection redisConnection = connectionFactory.getConnection();
        User user = new User();
        try {
            user.setUserName(principal.getName());
            org.springframework.security.oauth2.provider.OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) principal;
            OAuth2Request oAuth2Request = oAuth2Authentication.getOAuth2Request();
            String clientId = oAuth2Request.getClientId();
            user.setCurClientId(clientId);
            String expireKey = ACCESS_TOKEN_SECONS + clientId;

            //获取scope
            Map detailsMap = (Map) oAuth2Authentication.getUserAuthentication().getDetails();
            String scope = (String) detailsMap.get("scope");
            user.setScope(scope);

            boolean isCluster = trueOrFalse.isCluster();
            int expire;
            if (isCluster) {
                JedisCluster jedis = (JedisCluster) redisConnection.getNativeConnection();
                expire = Integer.parseInt(jedis.get(expireKey));
            } else {
                Jedis jedis = (Jedis) redisConnection.getNativeConnection();
                expire = Integer.parseInt(jedis.get(expireKey));
            }
            user.setTokenExpire(expire);
        } finally {
            redisConnection.close();
        }

        long currentEnd = System.currentTimeMillis();
        FunctionTimeUtil.functionTime("AuthUserController","current",currentBegin,currentEnd);
        return user;
    }
}
